/**
 * @用户手机本地目录
 */
const FINO_USER_PATH = `${wx.env.USER_DATA_PATH}/finoviewImages/`;

const donwloadTask = {};

/**
 * @通过url路径读取本地文件
 * @param {*} url 
 * @param {*} onlyToken 是否只处理携带token的文件 true只处理携带token的文件，false全部处理
 */
export const getFilePathByUrl = (url = "", onlyToken = true) => {
	const canIUse = wx.canIUse('getFileSystemManager');

	if (canIUse) {
		const splits = url.split("?");
		const basicUrl = splits[0] ? splits[0] : "";
		const query = splits[1] ? splits[1] : "";

		const hasToken = query.indexOf("token=") >= 0;
		let handleFlag = false;
		if(onlyToken) {
			if(hasToken) {
				handleFlag = true;
			}
		} else {
			handleFlag = true;
		}

		if(handleFlag) {
			const fileName = basicUrl.substring(basicUrl.lastIndexOf("/") + 1);
			const localFilePath = getFilePath(fileName);
	
			if (localFilePath) {
				return localFilePath;
			} else {
				//启动一个定时器线程去下载图片，并且返回原始url
				startDownloadTask(url, fileName);
	
				return url;
			}
		} else {
			return url;
		}
	} else {
		return url;
	}
}

/**
 * @通过文件名称读取本地文件
 * @param {*} fileName 
 */
const getFilePath = (fileName) => {
	mkDir();
	const localFilePath = `${FINO_USER_PATH}${fileName}`;

	const isExist = existFile(localFilePath);

	if (isExist) {
		const isExpire = expireFile(localFilePath);

		if (!isExpire) {
			return localFilePath;
		} else {
			removeFile(localFilePath);
		}
	}

	return null;
}

/**
 * @清理过期的文件
 */
export const cleanExpireFile = () => {
	const canIUse = wx.canIUse('getFileSystemManager');

	if (canIUse) {
		mkDir();
		const fileSystemManager = wx.getFileSystemManager();
		const dirPath = FINO_USER_PATH.substring(0, FINO_USER_PATH.length - 1);
	
		const fileList = fileSystemManager.readdirSync(dirPath);
	
		let size = 0;
		if (fileList && fileList.length > 0) {
			for (let fileName of fileList) {
				const localFilePath = `${FINO_USER_PATH}${fileName}`;
	
				const isExpire = expireFile(localFilePath);
	
				if (isExpire) {
					removeFile(localFilePath);
				} else {
					const fileStat = fileSystemManager.statSync(localFilePath, false);
					size += fileStat.size;
				}
			}
		}
	
		console.log("当前用户finoviewImages文件占用量约：" + (Math.round((size / 1024 / 1024) * 1000) / 1000) + "M")
	} else {
		console.log("当前基础库不支持用户本地存储功能")
	}
}

/**
 * @启动一个下载线程
 * @param {*} url 
 * @param {*} fileName
 */
const startDownloadTask = (url, fileName) => {
	//启动一个定时器线程去下载图片
	setTimeout(async () => {
		const filePath = `${FINO_USER_PATH}${fileName}`;
		if (donwloadTask[filePath]) return;

		donwloadTask[filePath] = true;

		const res = await donwloadFile(url);

		if (res.status) {
			const tempFilePath = res.filePath;

			saveFile(tempFilePath, filePath);
		}

		donwloadTask[filePath] = false;
	})
}

/**
 * @校验目录并创建
 */
const mkDir = () => {
	const fileSystemManager = wx.getFileSystemManager();
	const dirPath = FINO_USER_PATH.substring(0, FINO_USER_PATH.length - 1);

	try {
		fileSystemManager.accessSync(dirPath);
	} catch (e) {
		fileSystemManager.mkdirSync(dirPath);
	}
}

/**
 * @检验文件是否存在
 * @param {*} filePath 
 */
const existFile = (filePath) => {
	const fileSystemManager = wx.getFileSystemManager();
	let result = true;
	try {
		fileSystemManager.accessSync(filePath);
	} catch (e) {
		result = false;
	}

	return result;
}

/**
 * @查看文件否是过期
 * @param {*} filePath 
 */
const expireFile = (filePath) => {
	const fileSystemManager = wx.getFileSystemManager();
	const fileStat = fileSystemManager.statSync(filePath, false);

	const lastModifiedTime = fileStat.lastModifiedTime * 1000;

	const nowTime = new Date().getTime();

	// 过期时间
	const expireTime = 30 * 24 * 60 * 60 * 1000;
	//const expireTime = 1000;

	if (nowTime >= lastModifiedTime + expireTime) {
		return true
	}

	return false;
}

/**
 * @删除文件
 * @param {*} fileName 
 */
const removeFile = (filePath) => {
	const fileSystemManager = wx.getFileSystemManager();
	fileSystemManager.unlinkSync(filePath);
}

/**
 * @下载文件
 * @param {*} url
 */
const donwloadFile = (url) => {
	return new Promise(resolve => {
		wx.downloadFile({
			url: url,
			success: (res) => {
				if(res.statusCode === 200) {
					const filePath = res.tempFilePath;

					resolve({
						status: true,
						filePath: filePath
					})
				} else {
					resolve({
						status: false,
						filePath: null
					})
				}
			},
			fail: (err) => {
				console.log(err);

				resolve({
					status: false,
					filePath: null
				})
			}
		})
	})
}

/**
 * @保存文件到本地
 * @param {*} tempFilePath 临时文件目录
 * @param {*} filePath 要存储的文件目录
 */
const saveFile = (tempFilePath, filePath) => {
	const fileSystemManager = wx.getFileSystemManager();

	fileSystemManager.saveFileSync(tempFilePath, filePath);
}